"""
/** Copyright 2020 Zhejiang Lab and Zhejiang University. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================
*/
"""
from user.models import User
from backend.settings import DEBHE_USERINFO_URL
from utils import logRequest
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import parser_classes
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.parsers import FileUploadParser,MultiPartParser,JSONParser
import re, datetime
import logging
import requests

logger_name = 'user.views'
logger = logging.getLogger('django.request')

# See https://jpadilla.github.io/django-rest-framework-jwt/
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'auth': {
            'token': token,
            'username': user.username,
            'user_id': user.id,
            'is_staff': user.is_staff,
        },
    }

emailPattern = re.compile(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$')

class UserInfo(APIView):
    permission_classes = (AllowAny,)
    @logRequest(logger_name)
    def post(self, request, format=None):
        user_info = request.data.get('user_info', None)
        if user_info is None:
            return Response({'error': 'Parameter errors'}, status=status.HTTP_400_BAD_REQUEST)
        username = user_info.get('username', None)
        email = user_info.get('email', None)
        password = user_info.get('password', None)
        if None in (username, email, password):
            return Response({'error': 'Parameter errors'}, status=status.HTTP_400_BAD_REQUEST)
       
        # if emailPattern.match(email) is None:
        #     return Response({'error': 'Invalid email format'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = User.objects.create_user(username=username, email=email, password=password)

        except Exception as e:
            logger.debug(e)
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        return Response({'response': 'success'}, status=status.HTTP_201_CREATED)

    @logRequest(logger_name)
    def put(self, request, format=None):
        r = requests.get(url=DEBHE_USERINFO_URL, headers={"Authorization": request.data.get('token', None)})
        data = r.json()
        username = data.get('username', None)
        email = data.get('email', None)
        password = data.get('password', None)
        is_staff = data.get('is_staff', None)
        logger.debug('{} {} {} {}'.format(username, email, password, is_staff))
        if None in (username, email, password, is_staff):
            return Response({'error': 'Parameter errors'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(username=username)
            logger.debug(user)
        except User.DoesNotExist:
            try:
                if is_staff:
                    user = User.objects.create_superuser(username=username, email=email, password=password)
                else:
                    user = User.objects.create_user(username=username, email=email, password=password)
            except Exception as e:
                logger.debug(e)
                return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({'response': 'account created', 'username': username, 'password': password}, status=status.HTTP_201_CREATED)
        else:
            res = []
            try:
                if is_staff != user.is_staff:
                    user.is_admin = is_staff
                    user.is_staff = is_staff
                    user.is_superuser = is_staff
                    res.append('permission')

                if email != user.email:
                    user.email = email
                    res.append('email')

                if not user.check_password(password):
                    user.set_password(password)
                    res.append('password')

                user.save()
            except Exception as e:
                return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if res:
                    return Response({'response': '/'.join(res) + ' reset', 'username': username, 'password': password}, status=status.HTTP_200_OK)
                else:
                    return Response({'response': 'Already existed', 'username': username, 'password': password}, status=status.HTTP_200_OK)
